package com.ymatou.shop.ui.activity.seller;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.ymatou.shop.Constants;
import com.ymatou.shop.R;
import com.ymatou.shop.api.ApiRequest;
import com.ymatou.shop.api.ApiResponse;
import com.ymatou.shop.cache.ImageCache;
import com.ymatou.shop.cache.RequestInfo;
import com.ymatou.shop.cache.exception.CacheException;
import com.ymatou.shop.model.Comment;
import com.ymatou.shop.model.Product;
import com.ymatou.shop.model.Seller;
import com.ymatou.shop.ui.activity.BaseHeaderActivity;
import com.ymatou.shop.ui.activity.ShowProductImageActivity;
import com.ymatou.shop.ui.adapter.BaseAdapter;
import com.ymatou.shop.ui.view.item.DetailCommentItemView;
import com.ymatou.shop.util.DateUtil;
import com.ymatou.shop.util.DeviceUtil;
import com.ymatou.shop.util.GlobalUtil;

public class EventDetailActivity extends BaseHeaderActivity {
	
	private static final int REQUEST_ID_DETAIL = 0x01;
	private static final int REQUEST_ID_COMMENT = 0x02;
	
	private static final int COMMENT_PAGE_NUM = 10;
	
	private View mContainerRootView;
	private View mButtonRootView;
	private ImageView mHeaderImageView;
	private TextView mTitleTextView;
	private TextView mPublishTextView;
	private TextView mPriceTextView;
	private TextView mDownPaymentTextView;
	private TextView mStockNumTextView;
	private Gallery mImageGallery;
	private LinearLayout mImageIndicatorView;
	private ListView mCommentListView;
	
	private ImageAdapter mImageAdapter;
	private CommentAdapter mCommentAdapter;
	
	private Seller mSeller;
	private String mProductId;
	
	private Product mProduct;
	private String mLastCommentId;
	
	private volatile boolean mDetailLoaded;
	private volatile boolean mCommentLoaded;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_event_product_detail);
		
		mProductId = getIntent().getStringExtra(Constants.EXTRA_ID);
		mSeller = (Seller) getIntent().getSerializableExtra(Constants.EXTRA_DATA);
		
		setupViews();
		setupData(false);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		if (mImageAdapter != null) {
			mImageAdapter.notifyDataSetChanged();
		}
	}
	
	@Override
	protected void setupViews() {
		super.setupViews();
		getTitleTextView().setText(R.string.title_event_detail);
		getTitleLeftImageButton().setImageResource(R.drawable.back_icon);
		getTitleLeftImageButton().setVisibility(View.VISIBLE);
		getTitleLeftImageButton().setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		if (getAccount().isLogin()) {
			getTitleRightImageButton2().setImageResource(R.drawable.ren);
			getTitleRightImageButton2().setVisibility(View.VISIBLE);
			getTitleRightImageButton2().setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					GlobalUtil.startUserInfoActivity(v.getContext());
				}
			});
		} else {
			getTitleRightButton().setText(R.string.btn_login);
			getTitleRightButton().setVisibility(View.VISIBLE);
			getTitleRightButton().setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					startLoginActivity();
				}
			});
		}
		
		setupSeller();
		
		mContainerRootView = findViewById(R.id.container_root);
		mButtonRootView = findViewById(R.id.button_root);
		mTitleTextView = (TextView) findViewById(R.id.title_txt);
		mPublishTextView = (TextView) findViewById(R.id.publish_time);
		mPriceTextView = (TextView) findViewById(R.id.price_txt);
		mDownPaymentTextView = (TextView) findViewById(R.id.downpayment_txt);
		mStockNumTextView = (TextView) findViewById(R.id.stock_num_txt);
		
		mImageGallery = (Gallery) findViewById(R.id.image_gallery);
		mImageGallery.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View v,
					int position, long id) {
				for (int i = 0, size = mImageIndicatorView.getChildCount(); i < size; i++) {
					ImageView imageView = (ImageView) mImageIndicatorView.getChildAt(i);
					if (i == position) {
						imageView.setImageResource(R.drawable.ic_screenshot_focused);
					} else {
						imageView.setImageResource(R.drawable.ic_screenshot_normal);
					}
					imageView.getDrawable().setCallback(null);
				}
			}
			
			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
			}
		});
		mImageGallery.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View v, int position,
					long id) {
				String imageUrl = (String) parent.getAdapter().getItem(position);
				
				Intent intent = new Intent(v.getContext(), ShowProductImageActivity.class);
				intent.putExtra(ShowProductImageActivity.EXTRA_URL_ARRAY, mProduct.mImageList);
				intent.putExtra(ShowProductImageActivity.EXTRA_URL_CURRENT, imageUrl);
				v.getContext().startActivity(intent);
			}
		});
		mCommentListView = (ListView) findViewById(R.id.comment_list);
		findViewById(R.id.buy_button).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				GlobalUtil.startSaveOrderActivity(v.getContext(), mProduct);
			}
		});
		findViewById(R.id.add_comment_root).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO 添加评论
				GlobalUtil.startSendCommentActivity(v.getContext(), mProductId);
			}
		});
		findViewById(R.id.forward_root).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO 转发
			}
		});
		findViewById(R.id.refresh_root).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				changeLoadingViewState(false);
				setupData(false);
			}
		});
		
		changeLoadingViewState(false);
	}
	
	@Override
	protected void setupData(boolean useCache) {
		RequestInfo requestInfo = ApiRequest.getSellerEventDetail(mProductId, useCache);
		getCacheManager().register(REQUEST_ID_DETAIL, requestInfo, this);
		
		RequestInfo commentRequestInfo = ApiRequest.getCommentList(mProductId, String.valueOf(COMMENT_PAGE_NUM), mLastCommentId);
		getCacheManager().register(REQUEST_ID_COMMENT, commentRequestInfo, this);
	}
	
	private void setupIndicatorView() {
		mImageIndicatorView = (LinearLayout) findViewById(R.id.image_indicator_root);
		
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.WRAP_CONTENT,
				LinearLayout.LayoutParams.WRAP_CONTENT);
		params.leftMargin = 5;
		params.rightMargin = 5;
		
		for (String url : mProduct.mImageList) {
			ImageView imageView = new ImageView(this);
			mImageIndicatorView.addView(imageView, params);
		}
	}
	
	private void setupSeller() {
		((TextView) findViewById(R.id.name_txt)).setText(mSeller.mName);
		((TextView) findViewById(R.id.address_txt)).setText(mSeller.mPosition);
		mHeaderImageView = (ImageView) findViewById(R.id.header_image);
		
		Drawable drawable = ImageCache.get(this, mSeller.mHeaderUrl, new ImageCache.OnIconLoadCompleteListener() {
			@Override
			public void onLoadComplete(String url, boolean success, Drawable drawable) {
				if (success) {
					mHeaderImageView.setImageDrawable(drawable);
				}
			}
		});
		if (drawable != null) {
			mHeaderImageView.setImageDrawable(drawable);
		}
	}
	
	@Override
	public void onCacheSuccess(int requestId, RequestInfo requestInfo,
			Object response) {
		if (requestId == REQUEST_ID_DETAIL) {
			mProduct = ApiResponse.getSellerProduct((String) response);
			if (mProduct == null) {
				changeErrorViewState(false);
			} else {
				if (mProduct.mImageList != null
						&& mProduct.mImageList.length > 0) {
					setupIndicatorView();
					
					mImageAdapter = new ImageAdapter(this, mProduct.mImageList);
					mImageGallery.setAdapter(mImageAdapter);
					mImageGallery.setVisibility(View.VISIBLE);
				} else {
					mImageGallery.setVisibility(View.GONE);
				}
				
				mTitleTextView.setText(mProduct.mDescription);
				mPublishTextView.setText(DateUtil.format(mProduct.mPublishTime, "MM-dd HH:mm:ss"));
				mPriceTextView.setText(String.valueOf(mProduct.mPrice));
				mDownPaymentTextView.setText(String.valueOf(mProduct.mDownPayment));
				mStockNumTextView.setText(String.valueOf(mProduct.mStockNum));
				
				mDetailLoaded = true;
				if (mCommentLoaded) {
					changeLoadingViewState(true);
				}
			}
		} else if (requestId == REQUEST_ID_COMMENT) {
			List<Comment> commentList = ApiResponse.getCommentList((String) response);
			//////////////
			Comment c = new Comment();
			c.mPublishUserName = "测试代码添加";
			c.mContent = "测试代码添加测试代码添加测试代码添加测试代码添加测试代码添加测试代码添加";
			commentList = new ArrayList<Comment>();
			commentList.add(c);
			commentList.add(c);
			commentList.add(c);
			commentList.add(c);
			commentList.add(c);
			
			///////////////
			if (commentList == null || commentList.size() == 0) {
				mCommentListView.setVisibility(View.GONE);
			} else {
				mCommentAdapter = new CommentAdapter(this, commentList);
				mCommentListView.setAdapter(mCommentAdapter);
				
				mLastCommentId = commentList.get(commentList.size() - 1).mCommentId;
			}
			
			mCommentLoaded = true;
			if (mDetailLoaded) {
				changeLoadingViewState(true);
			}
		} else {
			super.onCacheSuccess(requestId, requestInfo, response);
		}
	}
	
	@Override
	public void onCacheFailed(int requestId, RequestInfo requestInfo,
			CacheException error) {
		if (requestId == REQUEST_ID_DETAIL) {
			changeErrorViewState(false);
		} else if (requestId == REQUEST_ID_COMMENT) {
			mCommentLoaded = true;
		} else {
			super.onCacheFailed(requestId, requestInfo, error);
		}
	}
	
	@Override
	public View[] getContentViews() {
		return new View[] { mContainerRootView, mButtonRootView };
	}
	
	private class ImageAdapter extends ArrayAdapter<String> implements ImageCache.OnIconLoadCompleteListener {
		
		private Drawable mDefaultDrawable;
		private int mWidth;

		public ImageAdapter(Context context, String[] items) {
			super(context, 0, items);
			
			mDefaultDrawable = getResources().getDrawable(R.drawable.ic_launcher);
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ImageView itemView;
			if (convertView == null) {
				itemView = new ImageView(getContext());
				itemView.setScaleType(ScaleType.CENTER_CROP);
				
				Rect rect =  DeviceUtil.getScreenRect(getContext());
				int screenWidth = rect.width();
				int screenHeight = rect.height();
				
				Gallery.LayoutParams params = new Gallery.LayoutParams(screenWidth, screenWidth);
				itemView.setLayoutParams(params);
			} else {
				itemView = (ImageView) convertView;
			}
			
			String item = getItem(position);
			
			Drawable drawable = ImageCache.get(getContext(), item, this);
			if (drawable == null) {
				drawable = mDefaultDrawable;
			}
			
			itemView.setImageDrawable(drawable);
			
			
			return itemView;
		}
		
		@Override
		public void onLoadComplete(String url, boolean success,
				Drawable drawable) {
			if (success) {
				notifyDataSetChanged();
			}
		}
	}
	
	private class CommentAdapter extends BaseAdapter<Comment> {

		public CommentAdapter(Context context, List<Comment> items) {
			super(context, items);
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			DetailCommentItemView itemView;
			if (convertView == null) {
				itemView = new DetailCommentItemView(getContext());
			} else {
				itemView = (DetailCommentItemView) convertView;
			}
			
			Comment comment = getItem(position);
			itemView.setData(comment);
			
			return itemView;
		}

	}
}
